<template>
    <rx-layout>
      <div slot="header">
       <div style="overflow:hidden;">
         <a-button style="margin-right: 10px;float: right" @click="handClose">
             {{$ti18('rxForm.closeBtn','关闭')}}
         </a-button>
         <a-button style="margin-right: 10px;float: right" :loading="loading" type="primary" @click="handSave">
             {{$ti18('rxForm.saveBtn','保存')}}
         </a-button>
       </div>
      </div>
        <div slot="center">
            <a-form :form="form" style="display: block">
                <a-form-item style="display:none">
                    <a-input v-decorator="['projectId']"/>
                </a-form-item>
              <div align="center">
                                <span> <a-radio-group v-model="paramType">
                                <a-radio-button value="configuration">
                                   {{i18n('form.projectConfiguration','项目配置')}}
                                </a-radio-button>
                                   <a-radio-button value="request">
                                   {{i18n('form.globalRequestHeader','全局请求头')}}
                                </a-radio-button>
                            </a-radio-group></span>
              </div>
              <div v-show="paramType =='configuration'" style="margin-top: 10px">
                <a-row>
                  <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.projectAlias','项目别名')">
                      <a-input :placeholder="i18n('form.projectAlias','项目别名')" v-decorator="['projectAlias', {rules: [{required: true,message: i18n('form.projectAlias','项目别名','input')}]}]"/>
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.projectName','项目名称')">
                      <a-input :placeholder="i18n('form.projectName','项目名称')" v-decorator="['projectName', {rules: [{required: true, message:  i18n('form.projectName','项目名称','input')}]}]"/>
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.itemClassification','项目分类')">
                      <rx-category-select cat-key="API" :isGrant="true"
                                          v-decorator="['treeId', {rules: [{required: true, message:i18n('form.itemClassification','项目分类','input')}]}]"></rx-category-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.projectStatus','项目状态')">
                      <a-radio-group :placeholder="i18n('form.projectStatus','项目状态')" v-decorator="['status',{initialValue:'YES'}]">
                        <a-radio value="YES">
                            {{i18n('isProjectStatusMap.enable','启用')}}
                        </a-radio>
                        <a-radio value="NO">
                            {{i18n('isProjectStatusMap.disable','禁用')}}
                        </a-radio>
                      </a-radio-group>
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="24">
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.domain','域名路径')">
                      <a-input v-decorator="['domainPath',{rules: [{ required: true, message: i18n('form.domain','域名路径','input')}],},]" style="width: 100%">
                        <a-select
                            slot="addonBefore"
                            v-decorator="['domainTcp', { initialValue: 'http://' }]"
                            style="width: 90px"
                        >
                          <a-select-option value="http://">
                            http://
                          </a-select-option>
                          <a-select-option value="https://">
                            https://
                          </a-select-option>
                        </a-select>
                      </a-input>
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="24">
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1">
                                        <span slot="label">
                                            {{i18n('form.basicPath','基本路径')}}
                                            <a-tooltip :title="i18n('form.rootPath','基本路径为空表示根路径')">
                                              <a-icon type="question-circle-o" />
                                            </a-tooltip>
                                          </span>
                      <a-input :placeholder="i18n('form.basicPath','基本路径','input')" v-decorator="['basePath', {rules: [{required: false, message:  i18n('form.basicPath','基本路径','input')}]}]"/>
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="24">
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.description','描述')">
                      <a-textarea :placeholder="i18n('form.description','描述')" v-decorator="['description', {rules: [{required: false, message: i18n('form.description','描述','input')}]}]" :rows="4" />
                    </a-form-item>
                  </a-col>
                </a-row>
              </div>
              <div v-show="paramType=='request'">
                <rx-grid ref="header"
                         :showPage="false"
                         :columns="headerColumns"
                         :dataSource="globalHeaders"
                         style="height: 370px;"
                >
                                <span slot="key" slot-scope="{text,record,index,blur}">
                                  <a-select show-search v-model="record.key"
                                            option-filter-prop="children" :filter-option="filterOption" @focus="fieldFocus(record)"
                                            @change="fieldChange($event,record,index)" @blur="fieldBlur(record,index)">
                                      <a-select-option v-for="header in headerDatas" :value="header">{{header}}</a-select-option>
                                  </a-select>
                                </span>
                                <span slot="valueSource" slot-scope="{text,record,index,blur}">
                                    <a-select :options="valueSources" v-model="record.valueSource"></a-select>
                                </span>
                                <span slot="value" slot-scope="{text,record,index,blur}">
                                  <a-input v-model="record.value" v-if="record.valueSource == 'fixedVar'" />
                                  <a-input-group v-if="record.valueSource == 'script'" compact>
                                    <a-input style="width:80%;" v-model="record.value" :disabled="true" />
                                    <a-button @click="openScriptQuery(record)">...</a-button>
                                  </a-input-group>
                                    <template v-if="record.valueSource=='constantVar'">
                                        <a-select v-model="record.value"
                                                  :options="constantField"
                                                  :getPopupContainer="p=>p.parentNode"
                                        ></a-select>
                                    </template>

                                </span>
                                <span slot="action" slot-scope="{ text, record,index }" class="actionIcons">
                                    <span v-if="index<globalHeadersSize-1" @click.stop="delRow([record.idx_])">
                                        {{$ti18('rxList.delBtn', '删除')}}
                                    </span>
                                </span>
                </rx-grid>
              </div>
            </a-form>
        </div>
    </rx-layout>
</template>

<script>
    import {Dialog, RxGrid,RxLayout,Util} from "@lowcode/jpaas-common-lib";
    import FormCustomQueryApi from '@/api/form/core/formCustomQuery'
    import SysInterfaceProjectApi from '@/api/system/core/sysInterfaceProject'
    export default {
        name: "SysInterfaceProjectInfo",
        props:["layerid","destroy","appId"],
        components:{
            RxGrid,
            RxLayout
        },
        created() {
            this.loadConstants();
        },
        data(){
            return {
              paramType:'configuration',
                form: this.$form.createForm(this),
                headerColumns: [
                    {title: this.i18n('form.key','键'), dataIndex: 'key', width: 100, scopedSlots: {customRender: 'key'}},
                    {title: this.i18n('form.valueSource','值来源'), dataIndex: 'valueSource', width: 100, scopedSlots: {customRender: 'valueSource'}},
                    {title: this.i18n('form.value','值'), dataIndex: 'value', width: 100, scopedSlots: {customRender: 'value'}},
                    {title: this.i18n('form.operation','操作'), dataIndex: 'action', width: 100, scopedSlots: {customRender: 'action'}}
                ],
                globalHeaders:[{valueSource:'fixedVar'}],
                globalHeadersSize:1,
                curRecord:{},
                constantField:[],
                loading:false,
                labelCol: { span:6 },
                wrapperCol: { span:18 },
                labelCol1: { span:3 },
                wrapperCol1: { span:19 },
                valueSources:[
                    {value:"fixedVar",label:this.i18n('form.fixValue','固定值')},
                    {value:"script",label:this.i18n('form.script','脚本')},
                    {value:"constantVar",label:this.i18n('form.constant','常量')}
                ],
                headerDatas:["Accept", "Accept-Charset","Accept-Encoding","Accept-Language","Accept-Datetime","Authorization","Cache-Control","Connection","Cookie","Content-Disposition",
                    "Content-Length","Content-MD5","Content-Type","Date","Expect", "From","Host", "If-Match", "If-Modified-Since","If-None-Match","If-Range","If-Unmodified-Since","Max-Forwards",
                    "Origin","Pragma","Proxy-Authorization","Range","Referer","TE","User-Agent","Upgrade","Via","Warning","X-Requested-With","DNT","X-Forwarded-For","X-Forwarded-Host","X-Forwarded-Proto",
                    "Front-End-Https","X-Http-Method-Override","X-ATT-DeviceId","X-Wap-Profile","Proxy-Connection","X-UIDH","X-Csrf-Token"]
            }
        },
        methods:{
            i18n(name, text, key) {
                return this.$ti18(name, text, "sysInterfaceProject", key);
            },
            setData(pkId){
                SysInterfaceProjectApi.get(pkId).then(res=>{
                    if(res.success && res.code==200) {
                        var mdl = res.data;
                        if(mdl.globalHeaders){
                            this.globalHeaders=JSON.parse(mdl.globalHeaders);
                            this.globalHeaders.push({key:"",valueSource:'fixedVar',value:""});
                            this.globalHeadersSize=this.globalHeaders.length;
                        }
                        this.form.setFieldsValue(mdl);
                    }
                })
            },
            save(values){
                values.globalHeaders=JSON.stringify(this.parseGridData(this.$refs.header.getData()));
                values.appId = this.appId;
                return SysInterfaceProjectApi.save(values);
            },
            parseGridData(data) {
                var ary = [];
                var idx = 0;
                for (var i = 0; i < data.length; i++) {
                    var obj = {};
                    obj.key = data[i].key;
                    obj.valueSource = data[i].valueSource;
                    obj.value = data[i].value;
                    if (Util.isEmpty(obj.key)) continue;
                    ary[idx++] = obj;
                }
                return ary;
            },
            handClose(){
              Util.closeWindow(this,"cancel");
            },
            handSave(){
                this.form.validateFields((err, values) => {
                    if(err) {
                        this.loading = false ;
                        return;
                    }
                    if(this.validForm){
                        var flag=this.validForm(values);
                        if(!flag){
                            this.loading = false ;
                            return;
                        }
                    }
                    this.save(values).then(res => {
                        if(res.success && res.code==200){
                            this.loading = false ;
                        }
                    }).catch(() => {
                        this.$message.error(this.$ti18('rxMsa.sysError','系统错误，请稍后再试!'))
                        this.loading = false ;
                    }).finally(() => {
                        this.loading = false ;
                    })
                })
            },
            delRow(idx_) {
                var grid = this.$refs.header;
                grid.removeRows(idx_);
                this.globalHeadersSize-=1;
            },
            filterOption(input, option) {
                this.curRecord["searchField"]={label:input,key:input,change:true};
                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
            },
            fieldFocus(record){
                this.curRecord=record;
            },
            fieldBlur(record,index){
                if(record["searchField"] && record["searchField"].change){
                    record["searchField"].change=false;
                    var text=record["searchField"].key;
                    record.key=text;
                    this.fieldChange(text,record,index);
                }
            },
            fieldChange(value,record,index){
                if(record["searchField"] && record["searchField"].change){
                    record["searchField"].change=false;
                }
                var grid = this.$refs.header;
                if (grid.getData().length <= index + 1 && value) {
                    grid.addRow({key:"",valueSource:'fixedVar',value:""});
                    this.globalHeadersSize+=1;
                }
            },
            loadConstants() {
                FormCustomQueryApi.getConstants().then((data) => {
                    this.constantField = this.constantField.concat(
                        data.map((item) => {
                            return { label: item.val, value: item.key }
                        })
                    )
                })
            },
            openScriptQuery(record){
                Dialog.openScripttextDialog(
                    {
                        curVm: this,
                        widthHeight: ['800px', '600px'],
                        data: { script: record.value },
                    },
                    function (self, data) {
                        record.value = data
                    }
                )
            }
        }
    }
</script>

<style scoped>

</style>